<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Movie;
use App\Models\Area;
class SetMoviesArea extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'daka:set-movies-area';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '设置电影地区分类';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        Movie::query()
            ->where('area', '<>', null)
            ->doesntHave('areas')
            ->chunkById(100, function($movies) {
                $this->info(sprintf('正在更新 ID 范围为 %s 至 %s 的电影地区信息', $movies->first()->id, $movies->last()->id));
                foreach ($movies as $movie) {
                    $areas = collect(explode('/', $movie->area))->map(function($area_name) {
                        $area = Area::firstOrCreate(['name' => trim($area_name)]);
                        return $area->id;
                    });
                    $movie->areas()->sync($areas);
                }
            });
            $this->info('完成更新');
    }
}
